import {
  StyleSheet,
  Text,
  View,
  Button,
  Image,
  Dimensions,
  ScrollView,
  Modal,
  TouchableOpacity,
  Alert,
  Platform,
  TouchableWithoutFeedback,
  TextInput,
  ToastAndroid,
} from "react-native";
import React, { useEffect, useState, useCallback } from "react";
import { useRoute } from "@react-navigation/native";
import axios from "axios";
import ImageViewer from "react-native-image-zoom-viewer";
import * as Print from "expo-print"; // 导入打印模块
import * as FileSystem from "expo-file-system";
import { shareAsync } from "expo-sharing";
import { store } from "expo-router/build/global-state/router-store";
import Api from '../Api/api'
export default function Descist() {
  const route = useRoute();
  let { id } = route.params;
  let [list, setlist] = useState([]); //存储后端返回的数据
  let [isModalVisible, setIsModalVisible] = useState(false); //控制模态框的显示和隐藏
  let [selectedImage, setSelectedImage] = useState(""); //存储用户选择的图片
  const [isLoading, setIsLoading] = useState(false); //控制加载状态
  const [state, setstate] = useState(false); //评论是否显示
  const [ContextList, setContextList] = useState([]); //评论内容
  // 这是发表评论的区域
  const [comment, setcomment] = useState(""); //评论内容
  let [isModalVisible1, setIsModalVisible1] = useState(false); //控制模态框的显示和隐藏
  let a;
  try {
    // 尝试解析存储的值
    a = JSON.parse(storage.getString("login"));
  } catch (error) {
    // 如果解析失败或存储没有数据，使用默认值
    console.log("解析存储数据失败，使用默认值:", error);
    a = { names: '杨光' }; // 默认值改成对象形式
  }

  // 确保 a 是一个对象，并可以访问 `names` 属性
  let userName = a.names || '杨光'; // 如果没有 `names` 属性，使用默认值
  // 向后端发送数据
  let sencontent = async () => {
    try {
      let {
        data: { data },
      } = await Api.post(`/yg/getcontent`, { id });
      setlist(data);
    } catch (error) {
      console.log(error);
    }
  };
  // 向后端请求数据
  let getcomment = async () => {
    try {
      let {
        data: { data },
      } = await Api.get(`/yg/getcomment`);
      setContextList(data);
    } catch (error) {
      console.log(error);
    }
  };
  useEffect(() => {
    sencontent();
    getcomment();
  }, []);
  // 打开Modal并设置选中的图片
  const openModal = (imgUrl: string) => {
    console.log("Opening modal with image:", imgUrl);
    setSelectedImage(imgUrl);
    setIsModalVisible(true);
  };

  // 关闭Modal
  const closeModal = () => {
    setIsModalVisible(false);
  };

  // 下载PDF并保存到本地
  const getPdf = async () => {
    setIsLoading(true); // 开始加载
    try {
      // 构建 HTML 内容
      const htmlContent = `
        <html>
          <body>
            ${list
          .map((item) =>
            item.academicimg
              .map(
                (imgUrl) =>
                  `<div style="margin-bottom: 20px;">
                          <img src="${imgUrl}" style="width: 100%; height: auto;" />
                        </div>`
              )
              .join("")
          )
          .join("")}
          </body>
        </html>
      `;

      // 使用 Print 生成 PDF
      const { uri } = await Print.printToFileAsync({ html: htmlContent });

      // 创建文件名
      const filename = "学术期刊.pdf";

      // 检查文件是否已经存在
      const fileInfo = await FileSystem.getInfoAsync(
        FileSystem.documentDirectory + filename
      );
      if (fileInfo.exists) {
        Alert.alert(
          "文件已存在",
          `PDF 文件已经存在：\n${FileSystem.documentDirectory + filename}`
        );
        return; // 如果文件已经存在，停止执行后续的保存操作
      }

      // 直接调用 save 函数进行保存
      await save(uri, filename, "application/pdf");
    } catch (error) {
      Alert.alert("错误", "生成 PDF 文件失败");
      console.error("生成 PDF 文件失败:", error);
    } finally {
      setIsLoading(false); // 下载完成后关闭加载状态
    }
  };
  // 保存PDF到设备
  const save = async (uri, filename, mimeType) => {
    try {
      if (Platform.OS === "android") {
        const permissions =
          await FileSystem.StorageAccessFramework.requestDirectoryPermissionsAsync();
        if (permissions.granted) {
          const base64 = await FileSystem.readAsStringAsync(uri, {
            encoding: FileSystem.EncodingType.Base64,
          });
          // 创建文件并写入
          const newUri =
            await FileSystem.StorageAccessFramework.createFileAsync(
              permissions.directoryUri,
              filename,
              mimeType
            );
          await FileSystem.writeAsStringAsync(newUri, base64, {
            encoding: FileSystem.EncodingType.Base64,
          });

          Alert.alert("文件已保存", `文件已成功保存到: ${newUri}`);
        } else {
          shareAsync(uri); // 如果没有权限，可以让用户分享文件
        }
      } else {
        // 对于iOS，直接调用分享API进行分享
        await shareAsync(uri);
      }
    } catch (error) {
      console.error("保存文件时出错:", error);
      Alert.alert("错误", "文件保存失败");
    }
  };

  let sendComment = async () => {
    let obj = {
      xiangname: a.names,
      xiangtitle: comment,
    };
    console.log(obj);
    await Api
      .post(`/yg/sendcomment`, obj)
      .then((res) => {
        if (res.data.code === 200) {
          getcomment();
          setcomment("");
        } else {
          ToastAndroid.showWithGravity(
            "评论失败",
            ToastAndroid.LONG,
            ToastAndroid.CENTER
          );
        }
      });
  };
  return (
    <View style={styles.container}>
      {/**tu图片渲染 */}
      <View style={styles.main}>
        <ScrollView contentContainerStyle={{ paddingBottom: 60 }}>
          <View>
            {list.map((item, index) =>
              item.academicimg.map((imgUrl, imgIndex) => (
                <TouchableOpacity
                  key={`${index}-${imgIndex}`}
                  onPress={() => openModal(imgUrl)}
                >
                  <Image
                    resizeMode="contain"
                    style={styles.Itemimg}
                    source={{ uri: imgUrl }}
                  />
                </TouchableOpacity>
              ))
            )}
          </View>
        </ScrollView>
      </View>
      {/* Modal 用于展示放大的图片 */}
      <Modal
        visible={isModalVisible}
        animationType="fade"
        transparent={true}
        onRequestClose={closeModal}
      >
        <ImageViewer
          imageUrls={[{ url: selectedImage }]}
          enableImageZoom={true}
          enableSwipeDown={true}
          onSwipeDown={closeModal}
          onClick={() => {
            setIsModalVisible(false);
          }}
        />
      </Modal>
      {/* 底部位置 */}
      <View style={styles.foot}>
        {/* 评论 */}
        <TouchableOpacity
          onPress={() => {
            setstate(true);
          }}
        >
          <Text>
            <Image
              style={styles.inon}
              source={require("@/assets/images/评论.png")}
            ></Image>
            <Text>1234</Text>
          </Text>
        </TouchableOpacity>
        {/* 下载 */}
        <TouchableOpacity onPress={getPdf}>
          <Text>
            <Image
              style={styles.inon}
              source={require("@/assets/images/下载.png")}
            ></Image>
            <Text>下载</Text>
          </Text>
        </TouchableOpacity>
      </View>

      <Modal
        animationType="slide" // 滑动效果
        transparent={true} // 透明背景
        visible={state} // 模态框是否可见
        onRequestClose={() => {
          setstate(false); // 关闭模态框
        }}
      >
        <TouchableWithoutFeedback onPress={() => setstate(false)}>
          <View style={styles.Comment}>
            {/* 包裹评论内容的 View */}
            <TouchableWithoutFeedback>
              <View style={styles.Context}>
                <ScrollView>
                  {ContextList.map((item) => (
                    <View style={styles.ContextItem} key={item.id}>
                      <Image source={require("@/assets/images/头像.png")} />
                      <View style={styles.ContentItemRight}>
                        <Text style={styles.ContextItemText}>
                          {item.xiangname}
                        </Text>
                        <Text style={styles.ContextItemText}>
                          {item.xiangtitle}
                        </Text>
                      </View>
                    </View>
                  ))}
                </ScrollView>
                <View style={styles.ContextIteminp}>
                  <TextInput
                    value={comment}
                    onChangeText={setcomment}
                    placeholder="请发送内容"
                    multiline
                    style={styles.inp}
                  />
                  <TouchableOpacity
                    style={{
                      borderWidth: 1,
                      borderColor: "#ccc",
                      borderRadius: 10,
                      height: 30,
                      width: 50,
                      alignItems: "center",
                      justifyContent: "center",
                    }}
                    onPress={sendComment}
                  >
                    <Text style={styles.send}>发送</Text>
                  </TouchableOpacity>
                </View>
              </View>
            </TouchableWithoutFeedback>
          </View>
        </TouchableWithoutFeedback>
      </Modal>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    backgroundColor: "#FFFFFF",
  },
  main: {
    flex: 1,
  },
  Itemimg: {
    width: Dimensions.get("window").width - 10,
    height: 200,
    marginTop: 10,
    marginLeft: 5,
  },
  foot: {
    width: Dimensions.get("window").width,
    height: 50,
    flexDirection: "row",
    justifyContent: "space-around",
    alignItems: "center",
    backgroundColor: "#FFFFFF",
    position: "absolute",
    bottom: 0,
  },
  modalContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "rgba(0, 0, 0, 0.7)",
  },
  modalImage: {
    width: Dimensions.get("window").width - 20,
    height: Dimensions.get("window").height - 100,
  },
  modalCloseButton: {
    position: "absolute",
    top: 20,
    right: 20,
    backgroundColor: "rgba(255, 255, 255, 0.5)",
    padding: 10,
    borderRadius: "50%",
  },
  modalCloseText: {
    fontSize: 20,
    color: "#000",
  },
  inon: {
    width: 15,
    height: 15,
  },
  Comment: {
    flex: 1,
    justifyContent: "flex-end",
    height: Dimensions.get("window").height,
    backgroundColor: "rgba(0, 0, 0, 0.5)",
    alignItems: "center",
  },
  Context: {
    backgroundColor: "#FFFFFF",
    width: Dimensions.get("window").width,
    height: Dimensions.get("window").height / 2 + 100,
    borderBottomLeftRadius: 10,
    borderBottomRightRadius: 10,
  },
  ContextItem: {
    width: Dimensions.get("window").width,
    height: 70,
    flexDirection: "row",
    borderColor: "#ccc",
    alignItems: "center",
    borderWidth: 1,
  },
  ContextItemText: {
    fontSize: 15,
    color: "#000",
    marginBottom: 5,
    paddingLeft: 10,
  },
  ContextIteminp: {
    width: Dimensions.get("window").width,
    height: 55,
    flexDirection: "row",
    alignItems: "center",
  },
  inp: {
    width: Dimensions.get("window").width - 50,
    height: 45,
    borderRadius: 20,
    borderColor: "#ccc",
    borderWidth: 1,
  },
  send: {
    color: "skyblue",
    textAlign: "center",
  },
});
